package com.xxx.config.security.component;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**JWT登录授权过滤器
 * @author WXH
 * @version 1.0
 * @date 2022/2/23 19:58
 */
public class JwtAuthencationTokenFilter extends OncePerRequestFilter {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private JwtTokenUtils jwtTokenUtils;
    @Autowired
    private UserDetailsService userDetailsService;


    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        //前置拦截
        String authHeader = request.getHeader(tokenHeader);//前端获取//通过 request 获取请求头
        //验证头部，不存在，或者是否以tokenHead：Bearer开头的
        if(authHeader !=null && authHeader.startsWith(tokenHead)){
            //存在，就做一个字符串的截取，其实就是获取了登录的token
            String authToken = authHeader.substring(tokenHead.length());
            //jwt根据token获取用户名
            String username = jwtTokenUtils.getUSerNameFromToken(authToken);
            //如果用户名不为空并且能拿到用户名，此时token存在用户名但是未登录
            if(username != null && SecurityContextHolder.getContext().getAuthentication() == null){
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);//登录
                //判断token是否有效，如果有效把他重新放到用户对象里面
                if(jwtTokenUtils.validteToken(authToken,userDetails)){
                    UsernamePasswordAuthenticationToken authenticationToken =new
                            UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());//内容，密码，权限
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }

        }
        //放行
        filterChain.doFilter(request,response);
    }
}
